'use strict';
const { group } = require('console');
const rq = require('request-promise');
const sha1 = require('sha1');

// 从环境变量获取敏感信息（安全！）
const APP_KEY = '82hegw5u8p3sx';
//const APP_SECRET = process.env.RONGCLOUD_SECRET; // 在云函数环境变量配置
const APP_SECRET = 'RF5gyvjbqtGvTo'
exports.main = async (event, context) => {
	try{
	var uri=''
	var method=''
	
	if(event.type==='token'){//获取token
		uri='https://api.rong-api.com/user/getToken.json'
		method='POST'
	}
	if(event.type==='group'){
		uri='https://api.rong-api.com/ultragroup/create.json'
	    method='POST'
	}
	if(event.type==='join'){
		uri=' https://api.rong-api.com/ultragroup/join.json'
	    method='POST'
	}
	if(event.type==='isMember'){
		uri=' https://api.rong-api.com/ultragroup/member/exist.json'
	    method='POST'
	}
		
    const timestamp = Date.now();
    const nonce = Math.floor(Math.random() * 1000000); // 整数Nonce
    // 生成签名
    const signature = sha1(APP_SECRET + nonce + timestamp);

    // 请求配置
    const options = {//获取token
      method: method,
      uri: uri,
      qs: event,
      headers: {
        'App-Key': APP_KEY,
        'Nonce': nonce,
        'Timestamp': timestamp,
        'Signature': signature,
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      json: true
    };
    // 发送请求
    const response = await rq(options);
    
    // 检查融云返回状态
    if (response.code !== 200) {
      throw { code: response.code, msg: '融云接口错误: ' + response.errorMessage };
    }

    return {
      code: 200,
      msg: 'success',
      data: response
    };

  } catch (error) {
    console.error('云函数错误:', error);
    return {
      code: error.code || 500,
      msg: error.msg || '服务器内部错误',
      data: null
    };
  }
   
  
};